package com.litchishell.easy;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LitchiShell
 * @description: 题目1：两数相加
 * @create 2022-08-15
 */
public class Solution001 {

    /**
     * 常规解法
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum(int[] nums, int target) {
        // 特殊情况处理
        int length = nums.length;
        if (length == 2) {
            return new int[]{0, 1};
        }

        for (int i = 0; i < length; i++) {
            int num1 = nums[i];
            int tempTarget = target - num1;
            for (int j = i + 1; j < length; j++) {
                if (nums[j] == tempTarget) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{-1, -1};
    }

    /**
     * 使用hash
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSumCopy(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i< nums.length; i++) {
            if(map.containsKey(target - nums[i])) {
                return new int[] {map.get(target-nums[i]),i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    public static void main(String[] args) {
        int[] nums = new int[]{3, 2, 4};
        int target = 6;
        int[] result = twoSum(nums, target);
        for (int i : result) {
            System.out.println(i);
        }
    }

}
